package mysql

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

func Init() (err error) {
	//dsn := "user:password@(localhost)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("mysql.user"),
		viper.GetString("mysql.password"),
		viper.GetString("mysql.host"),
		viper.GetInt("mysql.port"),
		viper.GetString("mysql.dbname"),
	)
	db, err := gorm.Open("mysql", dsn)
	// 也可以连接不成功就panic
	if err != nil {
		fmt.Println("连接MySql失败")
		zap.L().Error("连接MySql失败", zap.Error(err))
		return
	}
	db.DB().SetMaxOpenConns(viper.GetInt("mysql.max_open_conns"))
	db.DB().SetMaxIdleConns(viper.GetInt("mysql.max_idle_conns"))
	defer db.Close()
	return
}
